package net.zjitc.utils.db;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by Administrator on 2017/11/9.
 */
public class C3P0Utils {
    private static DataSource ds=null;
    public static  ThreadLocal<Connection> th = new ThreadLocal<Connection>();
    static{
        ds=new ComboPooledDataSource();
    }
    public static DataSource getDataSource(){
        return ds;
    }
    public static Connection getConnection() throws SQLException {
        Connection conn = th.get();
        if(conn != null){
            return conn; //带事务的链接
        }
        return ds.getConnection();//此链接不带事务
    }
    public static void startTransation() throws SQLException {
        Connection coon = th.get();
        if(coon!=null){
            throw new RuntimeException("事务已经开启,不需要再开启");
        }
        coon = ds.getConnection();
        coon.setAutoCommit(false);
        th.set(coon);
    }
    //提交事务
    public static void commitTransation() throws SQLException {
        Connection conn = th.get();
        if(conn==null){
            throw new RuntimeException("本身没有事务,无法提交");
        }
        conn.commit();
        conn.close();
        conn = null;
        th.remove();
    }
    //回滚操作
    public static void rollbackTransation() throws SQLException {
        Connection conn = th.get();
        if(conn==null){
            throw new RuntimeException("本身没有事务,无法回滚");
        }
        conn.rollback();
        conn.close();
        conn = null;
        th.remove();
    }
    //关闭
    public static void closeConnection(Connection connection) throws SQLException {
        Connection conn = th.get();
        if(conn!=connection){//只关闭普通的连接,带事务的连接在提交或回滚的时候关闭
            connection.close();
        }
    }
}
